<?php

namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Controller;
use think\Loader;

class Login extends Controller {

    public function index(){
        $username = cookie('username');
        $usertoken = cookie('token');
        $seven_days_before = date('Y-m-d H:i:s',strtotime("-7 day"));
        $result = Db::table('ticket_user')->where('name',$username)->find();
        if($result){
            if($usertoken == $result['token']){
                if($result['login_time'] > $seven_days_before){
                    $user_id = $result['id'];
                    $role_id = Db::table('ticket_role_user')->where('user_id',$user_id)->find();
                    session('username', $username);
                    session('role_id', $role_id['role_id']);
                    $this->success('登入成功', 'main/index');
                }
            }
        }
        else{
            return $this->fetch();
        }
    }
    /**
     * 后台首页
     */
    public function dologin(){
        //if (isset($_POST['username'])) {
        if (request()->isPost()){
            $username = input('post.username');
            $password = input('post.password');

            if (!$username) {
                $this->error('用户名不能为空');
            }
            if (!$password) {
                $this->error('密码不能为空');
            }

            $result = Db::table('ticket_user')->where('name',$username)->find();
            $password = md5(md5($password));
            if($result['password'] != $password){
                $this->error('用户名或密码错误');
            }
            $user_id = $result['id'];
            $token = md5($username.$password.date('Y-m-d H:i:s').rand(1000,9999));
            Db::table('ticket_user')->where('name',$username)->update(['token'=>$token]);
            Db::table('ticket_user')->where('name',$username)->setField('login_time',date('Y-m-d H:i:s',time()));

            $role_id = Db::table('ticket_role_user')->where('user_id',$user_id)->find();
            session('username', $username);
            session('role_id', $role_id['role_id']);
            cookie('username', $username);
            cookie('token', $token);

            $this->success('登入成功', 'main/index');
        }
        else{
            $this->error('登入失败');
        }
    }

    public function test(){
        echo "test";
    }

}